// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.numpy.codeInsight

import com.google.common.collect.ImmutableMap
import com.intellij.psi.PsiElement
import com.jetbrains.python.documentation.PythonDocumentationLinkProvider
import com.jetbrains.python.documentation.PythonDocumentationProvider
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader


class SciPyDocumentationLinkProvider : PythonDocumentationLinkProvider {

  private val nameToWebpageName: Map<String, String> by lazy {
    val b = ImmutableMap.builder<String, String>()
    try {
      BufferedReader(
        InputStreamReader(
          SciPyDocumentationLinkProvider::class.java
            .getResourceAsStream("/com/jetbrains/numpy/codeInsight/scipyNameMapping.tsv"), // generated by scipy_doc_mapping.py
          Charsets.UTF_8
        )
      ).use { inputStream ->
        inputStream.lines().forEach { line ->
          val kv = line.split("\t".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
          b.put(kv[0], kv[1])
        }
      }
    }
    catch (e: IOException) {
      throw RuntimeException(e)
    }

    b.build()
  }

  override fun getExternalDocumentationUrl(element: PsiElement?, originalElement: PsiElement?): String? {
    val qname = PythonDocumentationProvider.getFullQualifiedName(element)

    return if (qname != null && qname.firstComponent in listOf("numpy", "scipy")) {
      val webPage = nameToWebpageName.get(qname.toString())
      if (webPage != null) {
        "https://docs.scipy.org/doc/${qname.firstComponent}/reference/generated/$webPage.html"
      } else {
        "https://docs.scipy.org/doc/${qname.firstComponent}/reference/"
      }
    }
    else null

  }

}